package org.seven.jrdp.commons.spring.mvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.seven.jrdp.commons.constant.GlobalContants;
import org.seven.jrdp.commons.exception.BizException;
import org.seven.jrdp.commons.exception.WebException;
import org.seven.jrdp.commons.util.ServletUtils;

public class GlobalExceptionResolver implements HandlerExceptionResolver {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		logger.error("全局异常", ex);
		ModelAndView mv = new ModelAndView();
		mv.addObject("ex", ex);
		String message = "系统异常，请联系管理员";
		if (ex instanceof BizException) {
			message = ex.getMessage();
		} else if (ex instanceof WebException) {
			message = ex.getMessage();
		} else if (ex instanceof MaxUploadSizeExceededException) {
			MaxUploadSizeExceededException uploadException = (MaxUploadSizeExceededException) ex;
			long size = uploadException.getMaxUploadSize() / 1024 / 1024;
			message = "上传文件不允许超过" + size + "MB";
		}
		mv.addObject("message", message);
		String method = request.getMethod();
		if (ServletUtils.isAjax(request)) {
			method = GlobalContants.AJAX;
		}
		mv.addObject("method", method);
		String url = request.getServletPath();
		mv.setViewName(url.split("/")[1] + "/core/error");
		return mv;
	}
}